﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX.Direct3D9;
using System.Collections.Concurrent;
using System.Drawing;

namespace RaygunDiplomacy.Graphics
{
   public static class SpriteDrawer
   {
      #region Nested Objects

      struct DrawParameters
      {
         public Rectangle SourceRectangle;
         public SlimDX.Vector3 Center;
         public SlimDX.Vector3 Position;
         public SlimDX.Color4 Color;

         public DrawParameters(Rectangle sourceRectangle, SlimDX.Vector3 center, SlimDX.Vector3 position, SlimDX.Color4 color)
         {
            this.SourceRectangle = sourceRectangle;
            this.Center = center;
            this.Position = position;
            this.Color = color;
         }
      }

      #endregion

      #region Fields

      static SlimDX.Direct3D9.Sprite sprite = null;

      static ConcurrentDictionary<Texture, ConcurrentBag<DrawParameters>> drawings = new ConcurrentDictionary<Texture, ConcurrentBag<DrawParameters>>();

      #endregion

      #region Methods

      public static void Reset()
      {
         GraphicsProvider provider = GraphicsProvider.Instance;

         if (sprite != null)
         {
            sprite.Dispose();
         }

         sprite = new SlimDX.Direct3D9.Sprite(provider.Device);
      }

      public static void DrawAll()
      {
         sprite.Begin(SlimDX.Direct3D9.SpriteFlags.AlphaBlend | SlimDX.Direct3D9.SpriteFlags.SortDepthBackToFront);

         foreach (var kvp in drawings)
         {
            var texture = kvp.Key;

            foreach (var drawing in kvp.Value)
            {
               sprite.Draw(texture, drawing.SourceRectangle, drawing.Center, drawing.Position, drawing.Color);
            }
         }

         sprite.End();

         drawings.Clear();
      }

      public static void QueueDrawing(SlimDX.Direct3D9.Texture texture, Rectangle sourceRectangle, SlimDX.Vector3 center, SlimDX.Vector3 position, SlimDX.Color4 color)
      {
         if (!drawings.ContainsKey(texture))
         {
            drawings[texture] = new ConcurrentBag<DrawParameters>();
         }

         drawings[texture].Add(new DrawParameters(sourceRectangle, center, position, color));
      }

      #endregion
   }
}
